package com.hanfu.ucenter.web.web.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Component;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: jun
 * @Date: 2019/9/17 10:24
 * @Description: 生成 和解析jwt工具
 */

@Component
public class JwtHelper {

    /**
     * 解析jwt
     */

    public static Claims parseJWT(String jsonWebToken, String base64Security){
        try{
            Claims claims = Jwts.parser()
                    //.setSigningKey(DatatypeConverter.parseBase64Binary(base64Security))
                    .setSigningKey(base64Security.getBytes("UTF-8"))
                    .parseClaimsJws(jsonWebToken).getBody();
            return claims;
        }catch (Exception e){
            System.out.println(e);
            return null;
        }
    }

    /**
     *
     * @param name
     * @param userId
     * @param audience
     * @param issuer
     * @param TTLMillis
     * @param base64Security
     * @return
     */
    public  String createJWT(String name, Long userId,String cellPhone,
                                   String audience, String issuer, long TTLMillis, String base64Security){
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);

        //生成签名密钥
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(base64Security);
        Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

        //添加构成JWT的参数
        JwtBuilder builder = Jwts.builder().setHeaderParam("typ", "JWT")
                .claim("userName", name)
                .claim("id", userId)
                .claim("cellPhone",cellPhone)
                .setIssuer(issuer)
                .setAudience(audience)
                .signWith(signatureAlgorithm, signingKey);
        //添加Token过期时间
        if (TTLMillis >= 0) {
            long expMillis = nowMillis + TTLMillis;
            Date exp = new Date(expMillis);
            builder.setExpiration(exp).setNotBefore(now);
        }
        //生成JWT
        return builder.compact();
    }

    //根据token得到 用户 id，userName
    public  Map<String,Object> getUserIdAndByToken(String token, String base64Security){
        Claims claims=parseJWT(token,base64Security);
        if (claims!=null){
            Map<String,Object> map=new HashMap();
            Object id=claims.get("id");
            Object userName=claims.get("userName");
            Object cellPhone=claims.get("cellPhone");
            map.put("id",id);
            map.put("userName",userName);
            map.put("cellPhone",cellPhone);
            return map;
        }
        return null;
    }

    public static void main(String[] args) {
        Claims claims=JwtHelper.parseJWT("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyaW5mbyI6eyJpZCI6MTM1NjMsIm1lbWJlcl9tb2JpbGUiOiIxNDcwNzA3MDA1NiIsImFsaXBheV91bmlvbmlkIjoiMjA4ODgwMjYwMDQyNzgyNSIsIndlaXhpbl91bmlvbmlkIjoib01QWkM1bGpJbmdpbnQwV3Bma3hPZ1dtYU1wayIsInJlYWxuYW1lIjoiXHU0ZjU1XHU2Nzk3XHU3MDhlIiwibWVtYmVyX2F2YXRhciI6Imh0dHBzOlwvXC90ZnMuYWxpcGF5b2JqZWN0cy5jb21cL2ltYWdlc1wvcGFydG5lclwvVDFwUHR1WGdWYVhYWFhYWFhYIiwibWVtYmVyX3NleCI6MSwiaW52aXRlcl9pZCI6MTIwNDksIm5pY2tuYW1lIjoiXHU2NzA5XHU2OGE2XHU1YzMxXHU1NmJjXHU3NzQwXHU3MGFiXHU4ZmM4XHU1M2JiXHU4ZmZkXHU1NTRhIiwicnpfc3RhdHVzIjoxLCJsZXZlbF9uYW1lIjoiVklQMSIsImxldmVsX2lkIjoxLCJpc19idXkiOjEsInRva2VuIjoiYWI2ZDkwZmFjMjI3YjdkZmIwNGFhODE4ZTU5ODUyMThmOTViNDhhMSJ9LCJ0aW1lIjoxNTY5OTg0OTI3LCJ0b2tlbiI6ImFiNmQ5MGZhYzIyN2I3ZGZiMDRhYTgxOGU1OTg1MjE4Zjk1YjQ4YTEifQ.cmtFdBH-VqXD-OFwoU-ht_9qfa9VRdbZPqi2DsT41Kg","378e6f10665fbef30fbbdc6431308b6b");

        System.out.println(claims);

    }
}
